<template>
  <nav class="navbar">
    <div class="nav-brand">交通标志识别系统</div>
    <div class="nav-links">
      <router-link to="/" class="nav-link">首页</router-link>
      <router-link v-if="isLoggedIn" to="/prediction" class="nav-link">交通标志识别</router-link>
      <router-link v-if="isLoggedIn" to="/history" class="nav-link">历史记录</router-link>
      <router-link v-if="isAdmin" to="/settings" class="nav-link">系统设置</router-link>
      <template v-if="!isLoggedIn">
        <router-link to="/login" class="nav-link">登录</router-link>
        <router-link to="/register" class="nav-link">注册</router-link>
      </template>
      <template v-else>
        <span class="nav-link user-info">
          {{ username }}
          <span v-if="isAdmin" class="admin-badge">管理员</span>
        </span>
        <a href="#" @click.prevent="logout" class="nav-link">退出</a>
      </template>
    </div>
  </nav>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const isLoggedIn = ref(false)
const isAdmin = ref(false)
const username = ref('')

const updateUserState = () => {
  const token = localStorage.getItem('token')
  const userRole = localStorage.getItem('userRole')
  const storedUsername = localStorage.getItem('username')
  
  isLoggedIn.value = !!token
  isAdmin.value = userRole === 'admin'
  username.value = storedUsername || ''
  
  console.log('User state updated:', {
    isLoggedIn: isLoggedIn.value,
    isAdmin: isAdmin.value,
    username: username.value
  })
}

onMounted(() => {
  updateUserState()
})

// 监听 localStorage 变化
window.addEventListener('storage', updateUserState)

const logout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('userRole')
  localStorage.removeItem('username')
  updateUserState()
  router.push('/login')
}
</script>

<style scoped>
.navbar {
  background-color: #42b983;
  padding: 1rem 2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: white;
}

.nav-brand {
  font-size: 1.5rem;
  font-weight: bold;
}

.nav-links {
  display: flex;
  gap: 1.5rem;
  align-items: center;
}

.nav-link {
  color: white;
  text-decoration: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.nav-link:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.user-info {
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.admin-badge {
  background-color: #2e7d32;
  padding: 0.2rem 0.5rem;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: normal;
}
</style> 